/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

package opensocial.apps.friendforsale.command;

import opensocial.apps.common.Message;
import opensocial.apps.friendforsale.Tools;
import opensocial.apps.friendforsale.model.Activity;
import opensocial.apps.friendforsale.model.ActivityType;

import org.apache.log4j.Logger;

/**
 * viewer release his/her slave, accept request targetid=xxx
 * 
 * @author Sirius
 * 
 */
public class ReleaseSlaveCommand extends DostuffCommand {
  private static final Logger LOGGER = Logger
      .getLogger(ReleaseSlaveCommand.class);

  @Override
  public boolean execute() {
    if (!Tools.isSlave(viewer, target)) {
      LOGGER.error("can`t release target:" + target.getUserId()
          + " who is not your slave");
      output(new Message(MessageId.NOT_YOUR_SLAVE, null));
      return END;
    }

    this.hasError(false);
    target.setMasterid(null);
    target.setMastername(null);
    target.setNickname(null);

    viewer.setCapital(viewer.getCapital() - target.getPrice());
    viewer.setSlavenum(viewer.getSlavenum() - 1);
    
    Activity activity = this.newActivity(ActivityType.BUY);
    activity.setCommand(MessageId.RELEASE);

    persist.save(activity);
    persist.save(target);
    persist.save(viewer);

    LOGGER.info("viewer:" + viewer.getUserId() + " release slave:"
        + target.getUserId());
    output(new Message(MessageId.RELEASE, null));
    return NEXT;
  }

}
